# 静态化  首页 -
import os

from django.conf import settings
from django.template import loader

from apps.contents.models import ContentCategory
from apps.contents.utils import get_categories


def generate_static_index_html():
    # 1. 获取 首页 数据库数据
    # 1.商品分类 数据显示
    categories = get_categories()

    print('generate_static_index_html')

    # 2.广告数据显示
    contents = {}
    # 2.1 获取所有的广告分类
    ad_categories = ContentCategory.objects.all()
    # 2.2 遍历所有的广告分类--->对应的广告内容
    for ad_cat in ad_categories:
        contents[ad_cat.key] = ad_cat.content_set.filter(status=True).order_by('sequence')

    context = {
        'categories': categories,
        'contents': contents
    }

    # 2. 模板文件
    template = loader.get_template('index.html')
    # 3. 渲染数据==>str
    html_text = template.render(context)

    # 4. 写入文件
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html')
    with open(file_path, 'w') as f:
        f.write(html_text)
